
package com.yadong.smarthome.controldevice;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;

public class VoiceListenService extends Service {
    public static interface MessageListener {
        public void onNewMessageReceive(String message);
    }

    private SpeechRecognizer mIat;
    private MessageListener mMessageListener;

    public void setMessageListener(MessageListener messageListener) {
        this.mMessageListener = messageListener;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mIat = SpeechRecognizer.createRecognizer(this, mInitListener);
    }

    private Handler mHanlder = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (mMessageListener != null) { 
                mMessageListener.onNewMessageReceive((String)msg.obj);
            }
        };
    };

    public void stopListen() {
        mIat.stopListening();
    }

    public void startListen() {
        mIat.startListening(mRecoListener);
        int ret = mIat.startListening(mRecoListener);
        if (ret != ErrorCode.SUCCESS) {
            if (ret == ErrorCode.ERROR_COMPONENT_NOT_INSTALLED) {
                // 未安装则跳转到提示安装页面
            } else {
                Toast.makeText(this, "识别失败,错误码: ", Toast.LENGTH_LONG).show();
            }
        }
    }

    private RecognizerListener mRecoListener = new RecognizerListener() {
        // 听写结果回调接口(返回Json格式结果，用户可参见附录12.1)；
        // 一般情况下会通过onResults接口多次返回结果，完整的识别内容是多次结果的累加；
        // 关于解析Json的代码可参见MscDemo中JsonParser类；
        // isLast等于true时会话结束。
        public void onResult(RecognizerResult results, boolean isLast) {
            Log.d("Result:", results.getResultString());
            Message message = mHanlder.obtainMessage();
            if (null != results) {
                String text = JsonParser.parseIatResult(results.getResultString());
                if (!TextUtils.isEmpty(text)) {
                    message.obj = text;
                    message.sendToTarget();
                }
            }
        }

        // 会话发生错误回调接口
        public void onError(SpeechError error) {
            error.getPlainDescription(true); // 获取错误码描述}
        }

        // 开始录音
        public void onBeginOfSpeech() {
        }

        // 结束录音
        public void onEndOfSpeech() {
        }

        // 扩展用接口
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
        }

        @Override
        public void onVolumeChanged(int arg0, byte[] arg1) {

        }
    };

    /**
     * 初始化监听器。
     */
    private InitListener mInitListener = new InitListener() {
        @Override
        public void onInit(int code) {
            if (code != ErrorCode.SUCCESS) {
                Toast.makeText(VoiceListenService.this,
                        "初始化失败,错误码：" + code, Toast.LENGTH_LONG).show();
                return;
            }
            Log.d("mInitListener", "SpeechRecognizer init() code = " + code);
            mIat.setParameter(SpeechConstant.ENGINE_TYPE,
                    SpeechConstant.TYPE_CLOUD);
            mIat.setParameter(SpeechConstant.DOMAIN, "iat");
            mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
            mIat.setParameter(SpeechConstant.ACCENT, "mandarin ");
        }
    };

    public class MyBinder extends Binder {
        public VoiceListenService getService(){
            return VoiceListenService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

}
